<template>
  <div class="ebook">
      <title-bar :ifTitleAndMenuShow="ifTitleAndMenuShow"></title-bar>
      <div class="read-wrapper">
        <div id="read"></div>
          <div class="mask">
              <div class="left" @click="prevPage"><img src="/static/prev.png" alt="prev"></div>
              <div class="center" @click="toggleTitleAndMenu"></div>
              <div class="right" @click="nextPage"><img src="/static/next.png" alt="next"></div>
          </div>
      </div>
      <!-- <div class="read-wrapper">
          <div class="mask">
              <div class="left" @click="prevPage"><img src="/static/prev.png" alt="prev"></div>
              <div id="read" class="center" @click="toggleTitleAndMenu"></div>
              <div class="right" @click="nextPage"><img src="/static/next.png" alt="next"></div>
          </div>
      </div> -->
        <menu-bar :ifTitleAndMenuShow="ifTitleAndMenuShow" 
                @getCurrentLocation="getCurrentLocation"
                :fontSizeList = "fontSizeList" 
                :defaultFontSize="defaultFontSize"
                @setFontSize="setFontSize" 
                :themeList="themeList" 
                :defaultTheme="defaultTheme"
                @setTheme = "setTheme" 
                :bookAvailable = "bookAvailable" 
                @onProgressChange = "onProgressChange"
                @jumpTo="jumpTo"
                :navigation = "navigation"
                :parentProgress = "progress"
                ref="menuBar">
        </menu-bar>
  </div>
</template>
<script>
import TitleBar from '@/components/TitleBar'
import MenuBar from '@/components/MenuBar'
import router from '../router'
import Epub from 'epubjs'
let ssss= "ddd"
let DOWNLOAD_URL ='../../static/'+ssss+'.epub'
global.epub = Epub

export default {    
    components: {
        router,
        TitleBar,
        MenuBar
    },
    data(){
        return {
            ifTitleAndMenuShow:false,
            fontSizeList:[
                {
                    fontSize:12
                },
                {
                    fontSize:14
                },
                {
                    fontSize:16
                },
                {
                    fontSize:18
                },
                {
                    fontSize:20
                },
                {
                    fontSize:22
                },
                {
                    fontSize:24
                },
                {
                    fontSize:26
                }
            ],
            defaultFontSize:18,
            themeList:[{
                name:'default',
                style:{
                    body:{
                        'color':'#000',
                        'background':'#fff'
                    }
                }
            },{
                name:'green',
                style:{
                    body:{
                        'color':'#000',
                        'background':'#ceeaba'
                    }
                }
            },{
                name:'night',
                style:{
                    body:{
                        'color':'#fff',
                        'background':'#000'
                    }
                }
            },{
                name:'gold',
                style:{
                    body:{
                        'color':'#000',
                        'background': 'rgb(238, 232, 170)'//241.236,226
                    }
                }
            }],
            defaultTheme: 0,
            bookAvailable :false,
            navigation: null,
            progress:0
        }
    },
    methods:{
        getCurrentLocation(){
            if(this.rendition){
                this.showProgress()
            }
        },
        // 进度条跳转更新
        showProgress(){
            // 获取当前位置信息
            const currentLoction = this.rendition.currentLocation()
            // 获取当前位置进度百分比
            this.progress = this.bookAvailable ? this.locations.percentageFromCfi(currentLoction.start.cfi) : 0
            // 转化成0-100的数字
            this.progress = Math.round(this.progress*100)
        },
        // 根据链接跳转到指定位置
        jumpTo(href){
            this.rendition.display(href).then(()=>{
                this.showProgress()
            })
            this.hideTitleAndMenu()
        },
        hideTitleAndMenu(){
            // 隐藏标题栏和菜单栏
            this.ifTitleAndMenuShow = false
            // 隐藏菜单栏弹出的设置栏
            this.$refs.menuBar.hideSetting()
            // 隐藏目录
            this.$refs.menuBar.hideContent()
        },
        onProgressChange(progress){
            const percentage = progress / 100
            const location = percentage > 0 ? this.locations.cfiFromPercentage(percentage) : 0
            this.rendition.display(location)
        },
        setTheme(index){
             this.themes.select(this.themeList[index].name);
             this.defaultTheme = index;
        },
        registerTheme(){
            this.themeList.forEach(theme=>{
                this.themes.register(theme.name,theme.style)
            })
        },
        setFontSize(fontSize){
            this.defaultFontSize = fontSize
            if(this.themes){
                this.themes.fontSize(fontSize + 'px')
            }
        },
        toggleTitleAndMenu(){
            this.ifTitleAndMenuShow = !this.ifTitleAndMenuShow
            if(!this.ifTitleAndMenuShow){
                this.$refs.menuBar.hideSetting()
            }
        },
        prevPage(){
            // Rendition.prev
            if(this.rendition){
                this.rendition.prev().then(()=>{
                   this.showProgress()
                })
            }
        },
        nextPage(){
            // Rendition.next
            if(this.rendition){
                this.rendition.next().then(()=>{
                   this.showProgress()
                })
            }
        },
        // 电子书的解析和渲染
        showEpub(){
            // 生成book,Rendition,
            this.book = new Epub(DOWNLOAD_URL)
            //注册rendition，并绑定在read所在div上
            this.rendition = this.book.renderTo('read', {
                //渲染文本的长宽
                width:window.innerWidth,
                height: window.innerHeight,
                //http://huangxok.github.io/2016/05/19/Epub-Fixed-Layout/
                //rendition:spread 的意思是“展开”，表示怎样在一个屏幕上并列显示两个相邻的页面，以下简称“并列显示”。其值可以是：
                // none：不要并列显示。
                // landscape：仅当屏幕横置时并列显示。
                // portrait：仅当竖屏时并列显示。
                // both：总是并列显示。
                // auto：让阅读器选择是否并列显示。这是默认值。 
                    //当渲染时width小则单页   width大则双页       
                // spread:"landscape"
            })
            // console.log(this.book.renderTo()) 
            // id: "e72073d3-37d8-45bf-863e-e61487913bfd"
            //id: "cb381897-6691-4ad0-ace0-c3a38121fc77"
            // 通过Rendition.display渲染电子书
            this.rendition.display()
            // 获取Theme对象
            this.themes = this.rendition.themes
            // 设置默认字体
            this.setFontSize(this.defaultFontSize)
            // 设置默认主题色
            // this.themes.register(name,styles)
            this.registerTheme()
            // this.themes.select(name)
            this.setTheme(this.defaultTheme)
            // 获取locations对象 epubjs的钩子函数实现
            this.book.ready.then(() => {
                // 生成目录
                this.navigation = this.book.navigation
               // 生成Locations对象
                return this.book.locations.generate()//generate指定分页中的字符数，默认200
            }).then(result=>{
                console.log(result);
                // 保存locations对象
                this.locations = this.book.locations
                // 标记电子书为解析完毕状态
                this.bookAvailable = true
            })
        },
        isExistFile(filepath, filename) {
            if (filepath == null || filename == null || filepath === "" || filename === "") {
                return false
            }
            return true;
            // var xmlhttp;
            // if (window.XMLHttpRequest) {
            //     xmlhttp = new XMLHttpRequest();
            // } else {
            //     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            // }
            // xmlhttp.open("GET", filepath, false);
            // xmlhttp.send();
            // if (xmlhttp.readyState === 4) {
            //     console.log("sdsd"+xmlhttp.status)
            //     if (xmlhttp.status === 200) return true; //url存在
            //     else if (xmlhttp.status === 404) return false; //url不存在
            //     else return false;//其他状态
            // }
        },
    },
    mounted(){
        ssss = this.$route.query.book
        DOWNLOAD_URL = '../../static/' + ssss + '.epub'
        // this.showEpub()
        if (this.isExistFile(DOWNLOAD_URL, ssss)) {
            console.log("showss")
            this.showEpub()
        }
        else{
            this.$router.replace({path:"/404"})
        }
    }
}
</script>

<style scoped lang='scss'>
@import '../assets/styles/global.scss';
.ebook{
    margin: 0;
    position: relative;
    .read-wrapper{
        .mask{
            position: absolute;
            display: flex;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 9;
            .left{
                position: absolute;
                // top: 50%;
                top: 40%;
                flex:0 0 px2rem(50);
            }
            .center{
                flex: 1;
            }
            .right{
                position: absolute;
                left: 97.5%;
                top: 40%;
                flex:0 0 px2rem(50);
                @media screen and (max-width: 800px) {
                    left: 93.5%;
}
            }
        }
    }
}
</style>